<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Region, Agent, OrderProduct, Order, Message, Coupon, Product, Cate, Withdraw, AgentLog};
use think\Facade\Config as Configs;
use app\facade\Mns;
use think\Validate;
use think\Db;
use EasyWeChat\Factory;
use think\facade\Log;


class Rider extends Base
{

    public function agentlog()
    {
        $page = $this->request->get('page/d', 1);
        $agentid = $this->request->reder['id'];
        $list =  (new AgentLog())->where(['user_id' => $agentid])->field('id,type,money,created,info,source');
        $list = $list->order('id desc')->limit(15)->page($page)->select();
        foreach ($list as $row) {
            if ($row['type'] == 2 && $row['source'] > 0) {
                $status = (new Withdraw())->where('id', $row['source'])->value('status') ?? 0;
                $text = '';
                if ($status == 1) {
                    $text = '打款中';
                }
                if ($status == 2) {
                    $text = '提现成功';
                }
                if ($status == 3) {
                    $text = '提现失败';
                }
                if (!empty($text)) {
                    $row['info'] = $row['info'] . '(' . $text . ')';
                }
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function withdraw()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'money' => 'require|gt:50',
        ], [
            'money.require' => '提现金额不能为空',
            'money.gt' => '提现金额50起提',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $this->result([], 1, '提现通道暂时关闭');
        $agent = $this->request->reder;
        if ($agent['money'] < $data['money']) {
            $this->result([], 1, '提现金额不足');
        }
        if (empty($agent['openid'])) {
            $this->result([], 1, '请先微信授权');
        }
        Db::startTrans();
        try {
            $ids = (new Withdraw())->insertGetId([
                'user_id' => $agent['id'],
                'type' => 2,
                'money' => $data['money'],
                'fee' => round(($data['money'] * 6 / 1000), 2),
                'status' => 1
            ]);
            (new Agent())->MoneyEdit($agent['id'], 2, -$data['money'], '提现', $ids);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, '提现失败，请重试');
        }
        $this->result([], 0, '提现提交成功，请等待打款');
    }

    public function infos()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                // 'psmoney' => 'require',
                // 'maxkm' => 'require',
                // 'starsendmoney' => 'require',
                'mobile' => 'require',
                'nickname' => 'require',
                'lat' => 'require|gt:0',
                'lon' => 'require|gt:0',
                'address' => 'require',
                'send' => 'require|in:1,2',
            ], [
                'mobile.require' => '电话号码不能为空',
                'nickname.require' => '店铺名称不能为空',
                'lat.require' => '坐标不能为空',
                'lon.require' => '坐标不能为空',
                'lat.gt' => '坐标不能为空',
                'lon.gt' => '坐标不能为空',
                'address.require' => '地址不能为空',
                'send.require' => '是否配送不能为空',
                'send.require' => '是否配送类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!empty($data['send']) && $data['send'] == 2) {
                $data['psmoney'] = $data['psmoney'] ?? 0;
                $data['maxkm'] = $data['maxkm'] ?? 0;
                $data['starsendmoney'] = $data['starsendmoney'] ?? 0;
            }
            $res = (new Agent())->allowfield(true)->save($data, ['id' => $this->request->reder_id]);
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        } else {
            $agent = $this->request->reder;
            $datas = [
                'money' => $agent['money'],
                'send' => $agent['send'],
                'psmoney' => $agent['psmoney'],
                'maxkm' => $agent['maxkm'],
                'starsendmoney' => $agent['starsendmoney'],
                'accounts' => $agent['accounts'],
                'mobile' => $agent['mobile'],
                'nickname' => $agent['nickname'],
                'lat' => $agent['lat'],
                'lon' => $agent['lon'],
                'address' => $agent['address'],
            ];
            $this->result($datas, 0, '获取成功');
        }
    }

    public function getdatas()
    {
        if ($this->request->isGet()) {
            $datas = [
                'todyacount' => (new Order())->whereTime('paytime', '>=', date('Y-m-d'))->where(['agentid' => $this->request->reder_id, 'status' => [2, 3, 4]])->count(),
                'todytotal' => (new Order())->whereTime('paytime', '>=', date('Y-m-d'))->where(['agentid' => $this->request->reder_id, 'status' => [2, 3, 4]])->sum('total'),
                'yesacount' => (new Order())->whereTime('paytime', '<', date('Y-m-d'))->whereTime('paytime', '>=', date('Y-m-d', time() - 86400))->where(['agentid' => $this->request->reder_id, 'status' => [2, 3, 4]])->count(),
                'yestotal' => (new Order())->whereTime('paytime', '<', date('Y-m-d'))->whereTime('paytime', '>=', date('Y-m-d', time() - 86400))->where(['agentid' => $this->request->reder_id, 'status' => [2, 3, 4]])->sum('total'),
                'order' => (new Order())->where(['agentid' => $this->request->reder_id, 'status' => [2, 3, 4]])->count(),
                'total' => (new Order())->where(['agentid' => $this->request->reder_id, 'status' => [2, 3, 4]])->sum('total'),
            ];
            $this->result($datas, 0, '获取成功');
        }
    }

    public function goodsdetail()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'cate' => 'require',
                'images' => 'require',
                'price' => 'require|float|egt:0'

            ], [
                'title.require' => '产品名称不能为空',
                'cate.require' => '产品分类不能为空',
                'images.require' => '产品图片不能为空',
                'price.require' => '产品价格不能为空',
                'price.float' => '产品价格必须为数字',
                'price.egt' => '产品价格必须大于等于0',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $cate = (new Cate())->where(['id' => $data['cate'], 'agentid' => [0, $this->request->reder_id]])->find();
            if (empty($cate)) {
                $this->result([], 1, '产品分类不存在');
            }
            $ishot = 1;
            if (!empty($data['ishot']) && $data['ishot'] == 2) {
                $ishot = 2;
            }
            $post = [
                'agentid' =>  $this->request->reder_id,
                'title' =>  trim($data['title']),
                'cate' => $data['cate'],
                'images' => $data['images'],
                'price' => $data['price'],
                'descs' => $data['descs'] ?? '',
                'ishot' => $ishot,
            ];
            if (empty($data['id'])) {
                $res = (new Product())->allowfield(true)->save($post);
            } else {
                $goods = (new Product())->where(['id' => $data['id'], 'agentid' => $this->request->reder_id])->find();
                if (empty($goods)) {
                    $this->result([], 1, '产品不存在');
                }
                $res = (new Product())->allowfield(true)->save($post, ['id' => $data['id']]);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        } else {
            $id = $this->request->get('id/d', 0);
            $product = (new Product())->where(['id' => $id])->find();
            $cate = (new Cate())->where(['agentid' => [0, $this->request->reder_id]])->select();
            $this->result(['product' => $product, 'cate' => $cate], 0, '获取成功');
        }
    }

    public function goodshow()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id/d', 0);
            $product = (new Product())->where(['id' => $id, 'agentid' => $this->request->reder_id])->find();
            if (empty($product)) {
                $this->result([], 1, '产品不存在');
            }
            $status = $product['isshow'] == 2 ? 1 : 2;
            $res = (new Product())->where(['id' => $id])->update(['isshow' => $status]);
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败,请重试');
        }
    }

    public function getgoods()
    {
        $page = $this->request->get('page/d', 1);
        $title = $this->request->get('title/s', '');
        $isshow = $this->request->get('isshow/d', 1);
        $agentid = $this->request->reder['id'];
        $list =  (new Product())->where(['isdel' => 1, 'agentid' => $agentid])->field('id,price,isshow,title,images,sales,created');
        if (!empty($title)) {
            $list = $list->where('title', 'like', '%' . $title . '%');
        }
        if (!empty($isshow)) {
            $list = $list->where('isshow', '=', $isshow);
        }
        $list = $list->limit(15)->page($page)->select();
        $this->result($list, 0, '获取成功');
    }

    public function login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require'
        ], [
            'mobile.require' => '登录账号不能为空',
            'password.require' => '登录密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Agent())->where('mobile', $data['mobile'])->find();
        if (empty($user) || $user['password'] != md5(md5($data['password']))) {
            $this->result([], 1, '账号或密码错误');
        }
        $token = 'RIDER' . md5(md5($user['id'] . time()));
        Redis::setex($token, 86400 * 7, $user['id']);
        $this->result(['token' => $token], 0, '登录成功');
    }

    public function orderlist()
    {
        $status = $this->request->get('status/d', 1);
        $lat = $this->request->get('lat', 0) ?? 0;
        $lng = $this->request->get('lng', 0) ?? 0;
        if (empty($lat) || empty($lng)) {
            $lat = 0;
            $lng = 0;
        }
        Log::write($lat, 'getlons');
        $model = (new Order());
        $rider = $this->request->reder;
        $filed = 'ROUND(6371.004*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lng . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $list = $model->field('id,cmoney,sendmoney,ordersn,refund,lat,lon,name,mobile,street,address,posaddress,info,status,issystem,payment,total,ptotal,appointment,created,' . $filed);
        switch ($status) {
            case '1':
                $list = $list->order(['dist' => 'asc', 'appointment' => 'asc'])->where(['status' => 2, 'agentid' => $rider['id']]);
                break;
            case '2':
                $list = $list->order(['ordertime' => 'desc'])->where(['agentid' => $rider['id'], 'status' => 3]);
                break;
            case '3':
                $list = $list->order(['endtime' => 'desc'])->where(['agentid' => $rider['id'], 'status' => 4]);
                break;
            case '4':
                $list = $list->order(['caceltime' => 'desc'])->where(['agentid' => $rider['id'], 'status' => 5]);
                break;
            default:
                $list = $list->where(['id' => 0]);
                break;
        }
        $list = $list->paginate(50, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $street = getdrees($lists['street'], 1);
            $lists['province_text'] = $street['province'];
            $lists['city_text'] = $street['city'];
            $lists['area_text'] = $street['area'];
            $lists['street_text'] = $street['street'];
            $lists['appointment'] = !empty($lists['appointment']) ? $lists['appointment'] : '无';
            $lists['orderproduct'] = (new OrderProduct())->where('ordersn', $lists['ordersn'])->field('id,title,descs,images,price,number,cnumber')->select();
            $lists['status_text'] = $lists->status_text;
            $lists['payment_text'] = $lists->payment_text;
            if ($lists['dist'] < 100) {
                $lists['posaddress'] = $lists['posaddress'];
            }
            if ($lists['issystem'] == 2) {
                $lists['province_text'] = '*' . $street['province'];
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $model = (new Order());
        $rider = $this->request->reder;
        $lists = $model->where('id', $id)->field('id,agentid,sendmoney,type,payment,ordersn,ptotal,cmoney,total,appointment,created,info,status,street,name,mobile,posaddress,address,refund')->find();
        if (empty($lists)) {
            $this->result([], 1, '获取失败');
        }
        $street = getdrees($lists['street'], 1);
        $lists['province_text'] = $street['province'];
        $lists['city_text'] = $street['city'];
        $lists['area_text'] = $street['area'];
        $lists['street_text'] = $street['street'];
        $lists['appointment'] = !empty($lists['appointment']) ? $lists['appointment'] : '无';
        $lists['orderproduct'] = (new OrderProduct())->where('ordersn', $lists['ordersn'])->field('id,title,descs,images,price,number,cnumber')->select();
        $lists['status_text'] = $lists->status_text;
        $lists['payment_text'] = $lists->payment_text;
        $this->result($lists, 0, '获取成功');
    }

    public function orders()
    {
        $id = $this->request->get('id/d', 0);
        $rider = $this->request->reder;
        $order = (new Order())->where(['id' => $id, 'status' => 2, 'agentid' => $rider['id']])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在或用户已取消');
        }
        Db::startTrans();
        try {
            (new Order())->where(['id' => $order['id'], 'status' => 2])->update(['status' => 3, 'ordertime' => date('Y-m-d H:i:s')]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, '接单失败，请重试');
        }
        $this->result([], 0, '接单成功');
    }

    public function  message()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'message' => 'require',
                'type' => 'require|in:1,2,3',
            ], [
                'message.require' => '反馈内容为空',
                'type.require' => '反馈类型不能为空',
                'type.in' => '反馈类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['messtype'] = $data['type'];
            $data['type'] = 2;
            $data['user_id'] = $this->request->reder_id;
            if (!empty($data['images'])) {
                $images = json_decode($data['images'] ?? '', true) ?? [];
                if (is_array($images) && count($images) > 0) {
                    $data['images'] = json_encode($images, true);
                } else {
                    $data['images'] = '';
                }
            } else {
                $data['images'] = '';
            }
            $res = (new Message())->allowfield(true)->save($data);
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败');
        } else {
            $list = (new Message())->order('id desc');
            $list = $list->where(['user_id' =>  $this->request->reder_id, 'type' => 2])
                ->field('message,reply,mobile,created,images,messtype,type')
                ->paginate(20, false, ['query' => $this->request->param()])->each(function ($item) use ($list) {
                    $item['images'] = json_decode($item['images'], true) ?? [];
                    $item['type_text'] = $item->type_text;
                    return $item;
                });
            $this->result($list, 0, '查询完成');
        }
    }

    public function confirmorder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'status' =>  'require|in:4,5',
        ], [
            'id.require' => '订单id不能为空',
            'status.require' => '操作状态不能为空',
            'status.in' => '操作状态类型不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $rider = $this->request->reder;
        $order = (new Order())->where(['id' => $data['id'], 'agentid' => $rider['id'], 'status' => 3])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在或不可操作');
        }
        $user = (new Users())->where('id', $order['user_id'])->find();
        $endtime = date('Y-m-d H:i:s');
        $caceltime = date('Y-m-d H:i:s');
        if ($data['status'] == 4) {
            $endtime = date('Y-m-d H:i:s');
            $caceltime = $order['caceltime'];
        }
        if ($data['status'] == 5) {
            $endtime = $order['endtime'];
            $caceltime = date('Y-m-d H:i:s');
        }
        $msg = '操作成功';
        $data['refund'] = 1;
        if ($data['status'] == 5 && $order['total'] > 0 && $order['payment'] > 1) {
            $data['refund'] = 2;
            $msg = "操作成功，退款将原路返回";
        }
        Db::startTrans();
        try {
            (new Order())->where(['id' => $order['id'], 'status' => 3])->update([
                'refund' => $data['refund'],
                'status' => $data['status'],
                'endtime' => $endtime,
                'caceltime' => $caceltime
            ]);
            //积分赠送
            if ($data['status'] == 4 && !empty($user)) {
                (new Users())->IntergralEdit($user['id'], $user['integral'], $order['total'], 1, $order['id'], '下单赠送');
            }
            if ($data['status'] == 5 && $order['coupon'] > 0) {
                (new Coupon())->where('id', $order['coupon'])->update(['status' => 1]);
            }
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败，请重试');
        }
        $this->result([], 0, $msg);
    }

    public function orderupload()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'images' =>  'require',
        ], [
            'id.require' => '订单id不能为空',
            'images.require' => '照片不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where(['id' => $data['id'], 'orderid' => $this->request->reder_id])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在或不可操作');
        }
        if (!is_array($data['images'])) {
            $images = json_decode($data['images'] ?? '', true) ?? [];
        } else {
            $images = $data['images'];
        }
        if (is_array($images) && count($images) > 0) {
            $data['images1'] = json_encode($images, true);
        } else {
            $this->result([], 1, '照片上传出错,请重试或刷新页面');
        }
        Db::startTrans();
        try {
            (new Order())->where(['id' => $order['id']])->update([
                'images1' => $data['images1']
            ]);
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败，请重试');
        }
        $this->result([], 0, '操作成功');
    }

    public function getinfo()
    {

        $user = (new Agent())->field('password,created,updated,issystem', true)->where(['id' => $this->request->reder_id])->find();
        $this->result($user, 0, '获取成功');
    }
}
